package com.avengers.common.kit;

import com.avengers.core.kit.StringKit;

import java.io.FileNotFoundException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeoutException;

/**
 * @author yu.wang
 * @since 12/15/20 4:39 PM
 **/
public class ExceptionKit {
    public static final String RESET_MSG = "reset";
    public static final String TIMEOUT_MSG_1 = "times out";
    public static final String TIMEOUT_MSG_2 = "timed out";
    private static final String REFUSED = "Connection refused";

    public static boolean is404(Throwable e) {
        Throwable throwException = e;
        while (null != throwException) {
            if (throwException instanceof FileNotFoundException) {
                return true;
            }
            throwException = throwException.getCause();
        }

        return false;
    }

    public static boolean isTimeout(Throwable e) {
        Throwable throwException = e;
        while (null != throwException) {
            if (throwException instanceof TimeoutException || throwException instanceof SocketTimeoutException) {
                return true;
            }
            if (StringKit.notBlank(throwException.getMessage())) {
                if (throwException.getMessage().contains(TIMEOUT_MSG_1) || throwException.getMessage().contains(TIMEOUT_MSG_2)) {
                    return true;
                }
            }
            throwException = throwException.getCause();
        }

        return false;
    }

    public static boolean isRefused(Throwable e) {
        Throwable throwException = e;
        while (null != throwException) {
            if (throwException instanceof ConnectException
                    && StringKit.notBlank(throwException.getMessage())
                    && throwException.getMessage().contains(REFUSED)) {
                return true;
            }
            throwException = throwException.getCause();
        }

        return false;
    }

    public static boolean isTarget(Throwable e, Class... throwAbles) {
        if (null == e || null == throwAbles || throwAbles.length < 1) {
            return false;
        }
        Throwable throwException = e;
        while (null != throwException) {
            for (Class throwAble : throwAbles) {
                if (throwException.getClass().getName().equals(throwAble.getName())) {
                    return true;
                }
            }
            throwException = throwException.getCause();
        }
        return false;
    }
}
